import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  //http://geek.itheima.net/v1_0/channels
  List channels = [];
  int activeChannelId = 0;

  @override
  void initState() {
    getChannels();
    super.initState();
  }

  void getChannels() async {
    var dio = Dio();
    var response = await dio.get("http://geek.itheima.net/v1_0/channels");
    // print(response.data);
    setState(() {
      channels = response.data['data']['channels'] ?? [];
    });
  }

  void onChannelChange(int id) {
    setState(() {
      activeChannelId = id;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Container(
          color: Colors.white,
          child: Column(
            children: [
              ChannelNav(
                channels: channels,
                activeChannelId: activeChannelId,
                onChannelChange: onChannelChange,
              ),
              Expanded(
                child: ArticleList(activeChannelId: activeChannelId),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 频道导航
class ChannelNav extends StatelessWidget {
  const ChannelNav(
      {super.key,
      required this.channels,
      required this.activeChannelId,
      required this.onChannelChange});

  final List<dynamic> channels;
  final int activeChannelId;

  //回调函数修改频道
  final Function(int) onChannelChange;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      color: const Color.fromARGB(255, 255, 255, 255),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () => onChannelChange(channels[index]["id"]),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: Center(
                child: ChannelNavItem(
                  id: channels[index]["id"],
                  name: channels[index]["name"],
                  isActive: channels[index]["id"] == activeChannelId,
                ),
              ),
            ),
          );
        },
        itemCount: channels.length,
      ),
    );
  }
}

//文章列表
class ArticleList extends StatefulWidget {
  const ArticleList({super.key, required this.activeChannelId});

  final int activeChannelId;

  @override
  State<ArticleList> createState() => _ArticleListState();
}

class _ArticleListState extends State<ArticleList> {
  //https://geek.itheima.net/v1_0/articles?channel_id=0&timestamp=1729566236287
  List articles = [];

  void getArticles(int activeChannelId) async {
    var dio = Dio();
    var response = await dio.get(
        "http://geek.itheima.net/v1_0/articles?channel_id=$activeChannelId&timestamp=${DateTime.now().millisecondsSinceEpoch}");
    setState(() {
      articles = response.data['data']['results'] ?? [];
    });
  }

  // 频道ID更新时，重新获取文章
  @override
  void didUpdateWidget(covariant ArticleList oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.activeChannelId != oldWidget.activeChannelId) {
      getArticles(widget.activeChannelId);
    }
  }

  @override
  void initState() {
    getArticles(widget.activeChannelId);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color.fromARGB(255, 255, 255, 255),
      padding: const EdgeInsets.all(10),
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () => Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        ArticleDetail(article: articles[index]))),
            child: ArticleListItem(article: articles[index]),
          );
        },
        itemCount: articles.length,
      ),
    );
  }
}

// 频道导航项
class ChannelNavItem extends StatelessWidget {
  const ChannelNavItem(
      {super.key,
      required this.id,
      required this.name,
      required this.isActive});

  final int id;
  final String name;
  final bool isActive;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 5),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            name,
            textDirection: TextDirection.ltr,
            style: TextStyle(
              color: isActive ? Colors.black : Colors.grey,
              fontSize: isActive ? 18 : 15,
            ),
          ),
          if (isActive)
            Container(
              margin: const EdgeInsets.only(top: 4),
              height: 3,
              width: 20,
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 252, 102, 39),
                borderRadius: BorderRadius.circular(3),
              ),
            ),
        ],
      ),
    );
  }
}

// 文章列表项
class ArticleListItem extends StatelessWidget {
  const ArticleListItem({super.key, required this.article});

  final dynamic article;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          article["title"],
          textDirection: TextDirection.ltr,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 8),
        if (article["cover"] != null &&
            article["cover"]["images"] != null &&
            article["cover"]["images"].length >= 3)
          Row(
            children: List.generate(
              3,
              (index) => Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 4),
                  child: AspectRatio(
                    aspectRatio: 1.4,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.network(
                        article["cover"]["images"][index],
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          )
        else
          Container(), // 如果没有图片，显示一个空容器
        const SizedBox(height: 8),
        Row(
          children: [
            Text(article["aut_name"],
                style: const TextStyle(color: Colors.grey)),
            const SizedBox(width: 8),
            Text("${article["comm_count"]}评论",
                style: const TextStyle(color: Colors.grey)),
            const SizedBox(width: 8),
            Text(article["pubdate"],
                style: const TextStyle(color: Colors.grey)),
            const Spacer(),
            const Icon(Icons.close, color: Colors.grey),
          ],
        ),
      ],
    );
  }
}

//文章详情
class ArticleDetail extends StatelessWidget {
  const ArticleDetail({super.key, required this.article});

  final dynamic article;

  @override
  Widget build(BuildContext context) {
    //基础的假样式,仅展示文章id,art_id,以及返回按钮
    return Container(
      padding: const EdgeInsets.all(10),
      color: Colors.white,
      child: Column(
        children: [
          Text(
            "文章ID: ${article["art_id"]}",
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 10),
          ElevatedButton(
              onPressed: () => Navigator.pop(context), child: const Text("返回")),
        ],
      ),
    );
  }
}
